package sdc.com.petscalendar.fragments;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import sdc.com.petscalendar.R;
import sdc.com.petscalendar.objects.Pet;
import sdc.com.petscalendar.utils.Statics;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

public class PetEditIDFragment extends BaseFragment implements
		View.OnClickListener {
	private EditText mEdtName, mEdtWeight, mEdtBirthday;
	private Spinner mSpSex, mSpRace;
	private ImageView mIvAvatar;
	private View mBtnTakePicture;
	private View mBtnPickBirthday;
	private Bitmap mImageBitmap;
	ArrayList<String> races;
	public static final int RQ_GET_PET_PICTURE = 101;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		races = new ArrayList<String>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_edit_pet_id, container,
					false);
		}
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initComponents();
		addListeners();
		putInformation();
	}

	protected void initComponents() {
		mEdtName = (EditText) getView().findViewById(R.id.edt_name);
		mEdtBirthday = (EditText) getView().findViewById(R.id.edt_birthday);
		mEdtWeight = (EditText) getView().findViewById(R.id.edt_weight);

		mSpSex = (Spinner) getView().findViewById(R.id.sp_sex);
		mSpRace = (Spinner) getView().findViewById(R.id.sp_race);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				getActivity(), R.array.arr_race,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		mSpRace.setAdapter(adapter);

		mBtnTakePicture = getView().findViewById(R.id.btn_take_picture);
		mBtnPickBirthday = getView().findViewById(R.id.btn_pk_birthday);

		mIvAvatar = (ImageView) getView().findViewById(R.id.img_avatar);

		if (Statics.sPet.getAvatar() != null
				&& Statics.sPet.getAvatar().length() > 0) {
			if (new File(Statics.sPet.getAvatar()).exists()) {
				mIvAvatar.setImageBitmap(BitmapFactory.decodeFile(Statics.sPet
						.getAvatar()));
			}
		}
	}

	protected void addListeners() {
		mSpRace.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Statics.sPet.setRace(mSpRace.getSelectedItem().toString());

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		View.OnClickListener pickBirthday = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				pickBirthday(v);
			}
		};
		mBtnPickBirthday.setOnClickListener(pickBirthday);
		mEdtBirthday.setOnClickListener(pickBirthday);
		mBtnTakePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				takePicture(v);
			}
		});

		mEdtName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				Statics.sPet.setName(mEdtName.getText().toString());
			}
		});
		mEdtWeight.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				try {
					Statics.sPet.setWeight(Double.parseDouble(mEdtWeight
							.getText().toString()));
				} catch (Exception e) {
				}
			}
		});

		mSpSex.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Statics.sPet.setSex(arg2);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void takePicture(View v) {
		dispatchTakePictureIntent();
	}

	@SuppressLint("SimpleDateFormat")
	public void pickBirthday(View v) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(Statics.sPet.getBirthday());
		DatePickerDialog dpd = new DatePickerDialog(getActivity(),
				new DatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						Calendar calendar = Calendar.getInstance();
						calendar.set(year, monthOfYear, dayOfMonth);
						Statics.sPet.setBirthday(calendar.getTimeInMillis());
						SimpleDateFormat sdf = new SimpleDateFormat(
								"dd/MM/yyyy");
						mEdtBirthday.setText(sdf.format(calendar.getTime()));
					}
				}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		dpd.show();
	}

	@SuppressLint("SimpleDateFormat")
	private void putInformation() {
		mEdtName.setText(Statics.sPet.getName());
		mEdtWeight.setText(Statics.sPet.getWeight() + "");

		if (Statics.sPet.getSex() == Pet.SEX_MALE) {
			mSpSex.setSelection(0);
		} else {
			mSpSex.setSelection(1);
		}

		mSpRace.setSelection(1);

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(Statics.sPet.getBirthday());
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		mEdtBirthday.setText(sdf.format(calendar.getTime()));

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RQ_GET_PET_PICTURE
				&& resultCode == Activity.RESULT_OK) {
			Bundle extras = data.getExtras();
			mImageBitmap = (Bitmap) extras.get("data");
			mIvAvatar.setImageBitmap(mImageBitmap);
			new SaveFileTask().execute();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (Statics.sRequestCode != 0) {
			onActivityResult(Statics.sRequestCode, Statics.sResultCode,
					Statics.sData);
		}
	}

	private File saveImage(String name) {
		try {
			// Create an image file name
			File storageDir = new File(Environment
					.getExternalStorageDirectory().getPath() + "/petapp_data");

			if (!storageDir.exists()) {
				storageDir.mkdir();
			}
			storageDir = new File(storageDir.getPath() + "/photo");
			if (!storageDir.exists()) {
				storageDir.mkdir();
			}
			File imageFile = new File(storageDir.getPath() + "/" + name);

			if (imageFile.exists()) {
				imageFile.delete();
			}
			imageFile.createNewFile();
			mImageBitmap.compress(CompressFormat.JPEG, 100,
					new FileOutputStream(imageFile));
			return imageFile;
		} catch (Exception e) {
			return null;
		}
	}

	private String getPhotoStorageFile() {
		return Environment.getExternalStorageDirectory().getPath()
				+ "/phpetapp_dataoto/photo/pet_" + Statics.sPet.getId();
	}

	private class SaveFileTask extends AsyncTask<Void, Void, File> {
		ProgressDialog mDialog;

		@Override
		protected File doInBackground(Void... params) {
			if (mImageBitmap != null)
				return saveImage("pet_" + Statics.sPet.getId());
			return null;
		}

		@Override
		protected void onPostExecute(File result) {
			mDialog.dismiss();
			if (result != null) {
				Statics.sPet.setAvatar(result.getPath());

			} else {
				// Toast.makeText(getActivity(), "Save fail",
				// Toast.LENGTH_LONG);
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mDialog = new ProgressDialog(getActivity());
			mDialog.setMessage("Sauvetage...");
			mDialog.setCancelable(false);
			mDialog.show();
			super.onPreExecute();
		}

	}

	private void dispatchTakePictureIntent() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		getActivity().startActivityForResult(takePictureIntent,
				RQ_GET_PET_PICTURE);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (mImageBitmap != null) {
			mImageBitmap.recycle();
		}
		Statics.sRequestCode = 0;
	}

}
